class Oid < ActiveRecord::Base
  attr_accessible :name, :value, :host_id, :time_period, :last_value, :pid
  belongs_to :host

  def active?
    `ps aux | grep #{process_name} | grep -v grep` != ""
  end

  def activate
    self.pid = fork do
      puts "./script/snmp_get.rb #{host.ip} #{value} #{time_period}"
      exec "./script/snmp_get.rb #{host.ip} #{value} #{time_period}"
    end
    Process.detach(pid)
    save!
  end

  def process_name
    "#{host.ip}_#{value}"
  end

  def deactivate
    %x(kill -9 `ps aux | grep #{host.ip}_#{value}0 | grep -v grep | cut -d' ' -f3`)
  end




  def graph_link
    "rrd/#{process_name}.png"
  end

  def rrd
    "rrd_data/#{process_name}.rrd"
  end

  def create_graph
    img_name= "app/assets/images/rrd/#{process_name}.png"
    if File.exists? rrd
      RRD.graph(
        img_name,
        "--title", "#{host.name} - #{name}",
        "--interlace",
        "--imgformat", "PNG",
        "--width=450",
        "DEF:a=#{rrd}:a:AVERAGE",
        "CDEF:line=TIME,2400,%,300,LT,a,UNKN,IF",
        "AREA:a#00b6e4:alpha",
        "LINE3:line#ff0000")
    end
  end

  def get_graph
    create_graph
    graph_link
  end

end
